package bday.tvlport.beans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.model.UploadedFile;

import bday.tvlport.utils.LoggerUtility;

@ManagedBean(name = "fileUploadController")
@RequestScoped
public class UploadFilesBean {
   
	private static final int BUFFER_SIZE = 6124;
	private String imagetxt;
	private UploadedFile file1;
	private UploadedFile file2;
	private UploadedFile file3;
	static String[] validTypes = { "image/gif", "image/jpeg", "image/jpg", "image/png" };
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss-SSS");
	private String path;

	/** Creates a new instance of UploadBean */
	public UploadFilesBean() {
	}

	public UploadFilesBean(String imagetxt, UploadedFile file1, UploadedFile file2, UploadedFile file3) {
		this.imagetxt = imagetxt;
		this.file1 = file1;
		this.file2 = file2;
		this.file3 = file3;
	}
	
	@PostConstruct
	public void init() {
		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		//path = extContext.getRealPath("//WEB-INF//photos//");
		//path = "F://photos//";
		path ="photos//";
		File uploadDirectory = new File(path);
		if (!uploadDirectory.exists()) {
			uploadDirectory.mkdir();
		}
	}

	public void upload() {
		AtomicInteger totalFiles = new AtomicInteger(0);
		AtomicInteger validFiles = new AtomicInteger(0);
		validateFile(file1, totalFiles, validFiles);
		validateFile(file2, totalFiles, validFiles);
		validateFile(file3, totalFiles, validFiles);

		if (totalFiles.intValue() == 0 || totalFiles.intValue() != validFiles.intValue()) {
			FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Please upload only images(gif/jpg/jpeg/png) upto 5MB", "");
		    FacesContext.getCurrentInstance().addMessage(null, error);
		    setImagetxt(null);
		    return;
		}
		
		upload(file1, validFiles);
		upload(file2, validFiles);
		upload(file3, validFiles);
		resetFiles();
	}

	private void validateFile(UploadedFile file, AtomicInteger totalFiles, AtomicInteger validFiles) {
		if(file != null) {
			totalFiles.incrementAndGet();
			if(Arrays.asList(validTypes).contains(file.getContentType()) && file.getSize()<=5242880) {
				validFiles.incrementAndGet();
			}
		}
	}

	private void upload(UploadedFile file, AtomicInteger validFiles) {
		if(file == null) {
			return;
		}
		String filename = sdf.format(new Date())+"_"+getImagetxt()+"."+file.getContentType().substring(6);
		File result = new File(path + "\\" + filename);

		try {
		    FileOutputStream fileOutputStream = new FileOutputStream(result);

		    byte[] buffer = new byte[BUFFER_SIZE];

		    int bulk;
		    InputStream inputStream = file.getInputstream();
		    while (true) {
		        bulk = inputStream.read(buffer);
		        if (bulk < 0) {
		            break;
		        }
		        fileOutputStream.write(buffer, 0, bulk);
		        fileOutputStream.flush();
		    }

		    fileOutputStream.close();
		    inputStream.close();
		    FacesMessage msg = new FacesMessage("File Description: ", "File name: " + file.getFileName() + "<br/>File size: " + file.getSize() / 1024 + " Kb<br/>Content type: " + file.getContentType() + "<br/><br/>The file was uploaded.");
		    FacesContext.getCurrentInstance().addMessage(null, msg);
		    if(validFiles.decrementAndGet() == 0) {
		    	setImagetxt(null);
		    }

		} catch (Exception e) {
		    LoggerUtility.error(e.toString());
		    FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
		    FacesContext.getCurrentInstance().addMessage(null, error);
		    if(validFiles.decrementAndGet() == 0) {
		    	setImagetxt(null);
		    }
		}
	}

	private void resetFiles() {
		this.file1 = null;
		this.file2 = null;
		this.file3 = null;
	}
    
	public String getImagetxt() {
		return imagetxt;
	}

	public void setImagetxt(String imagetxt) {
		this.imagetxt = imagetxt;
	}
    
    public UploadedFile getFile1() {
		return file1;
	}

	public void setFile1(UploadedFile file1) {
		this.file1 = file1;
	}

	public UploadedFile getFile2() {
		return file2;
	}

	public void setFile2(UploadedFile file2) {
		this.file2 = file2;
	}

	public UploadedFile getFile3() {
		return file3;
	}

	public void setFile3(UploadedFile file3) {
		this.file3 = file3;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
}
